﻿using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using BusinessLogic.Interfaces;
using Domain;
using Domain.Entities;

namespace BusinessLogic.Implementations
{
    public class EFProducerRepository :IProducerRepository
    {

        private EFDbContext context;

        public EFProducerRepository(EFDbContext context)
        {
            this.context = context;
        }
        public IEnumerable<Producer> GetProducers()
        {
            return context.Producers.ToList();
        }

        public Producer GetProducerById(int id)
        {
            return context.Producers.FirstOrDefault(i => i.Id == id);
        }

        public Producer GetProducerByCountry(string producerCountry)
        {
            return context.Producers.FirstOrDefault(i => i.Country == producerCountry);
        }

        public void CreateProducer(Producer producer)
        {
            context.Producers.Add(producer);
        }

        public void CreateProducer(string producerCountry)
        {
            CreateProducer(new Producer{Country = producerCountry});
        }

        public void SaveProducer(Producer producer)
        {
            if (producer.Id == 0)
            {
                context.Producers.Add(producer);
            }
            else
            {
                context.Entry(producer).State = EntityState.Modified;
            }
            context.SaveChanges();
        }

        public void DeleteProducerById(int id)
        {
            context.Producers.Remove(GetProducerById(id));
            context.SaveChanges();
        }
    }
}
